package shape

import (
	"fmt"
	"io/ioutil"
	"sync"

	"github.com/golang/freetype/truetype"
	//"gitlab.w2gou.cn/xbc/go-lib/log"
	"golang.org/x/image/font"
)

var fontMaps = make(map[string]font.Face)
var fontLock sync.Mutex

/*
加载字体文件
*/
func GetFont(fontFile string, size int) font.Face {

	key := fmt.Sprintf("%v %v", fontFile, size)
	fontLock.Lock()
	f, isok := fontMaps[key]
	fontLock.Unlock()

	if isok {
		return f
	}

	fontBytes, e1 := ioutil.ReadFile(fontFile)

	if e1 != nil {
		//log.Info4("font_e", "getFont ReadFile error", "fontfile", fontFile, "size", size, "err", e1)
		return nil
	}

	f2, e2 := truetype.Parse(fontBytes)
	if e2 != nil {
		//log.Info4("font_e", "getFont truetype.Parse error", "fontfile", fontFile, "size", size, "err", e2)
		return nil
	}
	face := truetype.NewFace(f2, &truetype.Options{Size: float64(size)})

	if face != nil {
		fontLock.Lock()
		fontMaps[key] = face
		fontLock.Unlock()
	}

	return face
}
